package mac5855.app.controllers;

import javax.servlet.RequestDispatcher;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import mac5855.app.dao.DAOFactory;
import mac5855.app.dao.UsuarioDAO;
import mac5855.app.models.Usuario;

public class UsuarioController implements BusinessLogic {

	@Override
	public void execute(HttpServletRequest request, HttpServletResponse response)
	throws Exception {
		System.out.println("Executando a logica e redirecionando...");

		String action = request.getParameter("action");
		System.out.println("action:"+action);
		if(action == null) {


			Usuario usuario = new Usuario();

			usuario.setNome(request.getParameter("nome"));
			usuario.setEmail(request.getParameter("email"));
			//if(request.getParameter("senha") == request.getParameter("confirme_senha")) {
			usuario.setSenha(request.getParameter("senha"));
			//}
			usuario.setTipo(request.getParameter("tipo"));

			UsuarioDAO dao = DAOFactory.getDAOFactory(DAOFactory.JDBC).getUsuarioDAO();
			dao.create(usuario);
			RequestDispatcher rd = request.getRequestDispatcher("/admin/");
			rd.forward(request, response);
			System.out.println("Alterando contato ..." + usuario.getNome());

		}
		else if(action.equals("search")) {
			String search = request.getParameter("search");
			String tipo = request.getParameter("tipo");
			RequestDispatcher rd = request.getRequestDispatcher("/admin/index.jsp?search="+search+"&tipo="+tipo);
			rd.forward(request, response);
		}
		else if(action.equals("delete")) {
			String id = request.getParameter("id");
			UsuarioDAO dao = DAOFactory.getDAOFactory(DAOFactory.JDBC).getUsuarioDAO();
			
			try {
				dao.delete(id);
			} catch (NumberFormatException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			RequestDispatcher rd = request.getRequestDispatcher("/admin/");
			rd.forward(request, response);
		}
		
		

	}

}
